package com.tinem.platform.web.auth.login.oauth2.ext;

import com.tinem.platform.client.security.VerificationCodeClient;
import com.tinem.platform.module.starter.jpa.entity.rbac.RbacUser;
import com.tinem.platform.module.starter.jpa.repository.rbac.RbacUserRepository;
import com.tinem.platform.web.auth.login.LoginService;
import com.tinem.platform.web.auth.page.LoginUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className SmsCodeAuthenticationProvider
 * @description TODO
 * @site 
 * @company 
 * @create 2020-10-01 17:16
 */
@Component
public class OAuth2AuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private LoginService loginService;
    @Autowired
    RbacUserRepository rbacUserRepository;
    @Autowired
    VerificationCodeClient verificationCodeClient;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        OAuth2AuthenticationToken authenticationToken = (OAuth2AuthenticationToken) authentication;
        String userId = authenticationToken.getPrincipal();
        RbacUser user = rbacUserRepository.findById(userId).get();
        LoginUserInfo loginUserInfo = loginService.getLoginUser(user.getId());
        OAuth2AuthenticationToken oAuth2AuthenticationToken = new OAuth2AuthenticationToken(loginUserInfo.getUserId(),loginUserInfo,loginUserInfo.getAuthorities());
        oAuth2AuthenticationToken.setDetails(authenticationToken.getDetails());
        return oAuth2AuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return OAuth2AuthenticationToken.class.isAssignableFrom(authentication);
    }
}
